<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入物料名称"
            v-model="queryParams.keyword"
            clearable
            @keyup.enter.native="handleQuery"
            size="small">
            <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            placeholder="请选择物料类型"
            v-model="queryParams.materialType"
            clearable
            @change="handleMaterialTypeChange"
            size="small"
            style="width: 100%">
            <el-option
              v-for="item in materialTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <!-- 删除了更多下拉菜单及导入导出按钮 -->
        </el-col>
      </el-row>
    </div>
    
    <div class="main-content">
      <!-- 左侧分类树 -->
      <div class="category-tree-container">
        <div class="category-title">
          <span>物料分类</span>
          <el-button 
            type="text" 
            icon="el-icon-refresh" 
            @click="loadCategoryData" 
            style="float: right; padding: 3px 0" 
            title="刷新分类">刷新</el-button>
        </div>
        <el-tree
          v-loading="treeLoading"
          :data="categoryTreeData"
          :props="categoryProps"
          node-key="id"
          highlight-current
          default-expand-all
          @node-click="handleCategoryClick"
          class="category-tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span :title="data.material_classification_name" :class="{'parent-category': !node.parent.data.id, 'child-category': node.parent.data.id}">
              {{ data.material_classification_name }}
            </span>
            <span v-if="data.material_classification_code && data.id !== '0'" 
                  class="category-code" :title="data.material_classification_code">
              ({{ data.material_classification_code }})
            </span>
          </span>
        </el-tree>
      </div>
      
      <!-- 右侧物料表格 -->
      <div class="material-table-container">
        <div class="title-container">
          <span class="title"></span>
        </div>
        <div class="table-operations">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          <!-- 删除了导入导出按钮 -->
        </div>
        
        <el-table
          v-loading="loading"
          :data="materialList"
          border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" width="70" prop="index" />
          <el-table-column label="物料编号" align="center" width="140" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.materialCode" placement="top" :enterable="false">
                <span class="material-code-table">{{ scope.row.materialCode }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" align="center" width="150" prop="materialName" :show-overflow-tooltip="true" />
          <el-table-column label="规格型号" align="center" width="120" prop="specification" :show-overflow-tooltip="true" />
          <el-table-column label="单位" align="center" width="80" prop="unit" />
          <el-table-column label="物料类型" align="center" width="120" prop="materialType" :show-overflow-tooltip="true" />
          <el-table-column label="物料属性" align="center" width="120" prop="materialAttr" />
          <el-table-column label="物料分类" align="center" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.materialCategory || '未分类'" placement="top" :enterable="false">
                <span v-if="scope.row.materialCategory" style="color: #606266;">{{ scope.row.materialCategory }}</span>
                <span v-else-if="scope.row.categoryId || scope.row.subcategoryId" style="color: #409EFF; font-style: italic;">
                  <i class="el-icon-loading" style="margin-right: 3px;"></i>
                  加载中
                </span>
                <span v-else style="color: #909399; font-style: italic;">未分类</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleEdit(scope.row)"
                style="color: #409EFF;">编辑</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                style="color: #F56C6C;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 若依框架分页组件 - 使用独立变量跟踪分页参数 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    
    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 物料编号单独一行，以便更好地显示 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料编号" prop="materialCode">
              <el-input 
                v-model="form.materialCode" 
                placeholder="请输入物料编号" 
                :disabled="true"
                class="material-code-input">
                <el-button slot="append" icon="el-icon-refresh" @click="getAutoCode" v-if="!form.id">自动编号</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 物料名称单独一行 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option
                  v-for="item in unitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-select v-model="form.materialType" placeholder="请选择物料类型">
                <el-option
                  v-for="item in materialTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料属性" prop="materialAttr">
              <el-select v-model="form.materialAttr" placeholder="请选择物料属性">
                <el-option label="自制" value="1"></el-option>
                <el-option label="委外" value="2"></el-option>
                <el-option label="外购" value="3"></el-option>
                <el-option label="其他" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料分类" prop="categoryId">
              <div class="category-select-box">
                <el-popover
                  placement="bottom-start"
                  width="500"
                  trigger="click"
                  v-model="categoryPopoverVisible">
                  <div class="category-selector">
                    <div class="category-content">
                      <!-- 左侧父分类列表 -->
                      <div class="parent-categories">
                        <div class="category-list-title">父分类</div>
                        <el-radio-group v-model="selectedParentId" @change="handleParentCategoryChange">
                          <div v-for="category in parentCategories" :key="category.material_classification_id" class="parent-category-item">
                            <el-radio :label="category.material_classification_id">
                              <span class="category-name">{{ category.material_classification_name }}</span>
                              <span class="category-code">{{ category.material_classification_code }}</span>
                            </el-radio>
                            <i class="el-icon-arrow-right"></i>
                          </div>
                        </el-radio-group>
                      </div>
                      
                      <!-- 右侧子分类列表 -->
                      <div class="child-categories">
                        <div class="category-list-title">子分类</div>
                        <el-radio-group v-model="selectedChildId" @change="handleChildCategoryChange">
                          <div v-for="child in filteredChildCategories" :key="child.material_subcategory_id" class="child-category-item">
                            <el-radio :label="child.material_subcategory_id">
                              <span class="category-name">{{ child.material_subcategory_name }}</span>
                              <span class="category-code">{{ child.material_subcategory_code }}</span>
                            </el-radio>
                          </div>
                          <div v-if="filteredChildCategories.length === 0 && selectedParentId" class="no-subcategories">
                            该分类下暂无子分类
                          </div>
                        </el-radio-group>
                      </div>
                    </div>
                  </div>
                  <div slot="reference" class="category-input-reference">
                    <el-input 
                      v-model="form.materialCategory" 
                      placeholder="请选择物料分类" 
                      readonly>
                      <i slot="suffix" class="el-input__icon el-icon-arrow-down"></i>
                    </el-input>
                  </div>
                </el-popover>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="启用">启用</el-radio>
                <el-radio label="停用">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, addMaterial, updateMaterial, deleteMaterial, listAllUnits, getMaterialById } from '@/api/basic/material'
import { listAllParentCategories, listMaterialCategory, listAllCategoriesWithChildren } from '@/api/basic/materialCategory'
import { getAutoNumbers, getAutoNumbersConsume } from '@/api/basic/numbers' // 导入自动编码API
import Pagination from '@/components/Pagination'

export default {
  name: 'BasicWl',
  components: {
    Pagination
  },
  data() {
    return {
      // 加载状态
      loading: false,
      // 分类树加载状态
      treeLoading: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialCode: [
          { required: true, message: "物料编号不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,   // 物料编码
        materialName: undefined,   // 物料名称
        materialType: undefined,   // 物料类型
        categoryId: undefined,     // 分类ID (前端参数)
        material_classification_id: undefined, // 分类ID (后端参数)
        keyword: undefined,        // 关键字
        material_sfn: undefined,   // 规格型号
        // 移除了单位查询参数 material_unit
        material_mp: undefined,    // 物料属性
        material_fl: undefined     // 物料分类名称
      },
      // 总条数
      total: 0,
      // 物料类型选项
      materialTypeOptions: [
        { label: '生产物料', value: '1' },
        { label: '半成品', value: '2' },
        { label: '其他', value: '3' }
      ],
      // 单位选项
      unitOptions: [],
      // 物料分类树结构数据
      categoryTreeData: [
        {
          id: '0',
          label: '全部物料',
          children: []
        }
      ],
      categoryProps: {
        children: 'children',
        label: 'material_classification_name',
        isLeaf: (data, node) => {
          // 如果是标记为叶子节点的子分类，直接返回true
          if (data.leaf === true || data.isSubcategory === true) {
            return true;
          }
          
          // 如果已经加载了子节点，根据子节点数量判断
          if (data.children) {
            return data.children.length === 0;
          }
          
          // 否则默认父分类可能有子节点
          return false;
        }
      },
      // 表格数据
      materialList: [],
      // 分类级联选项
      categoryOptions: [],
      
      // 分类选择相关
      categoryPopoverVisible: false,
      selectedParentId: null,
      selectedChildId: null,
      parentCategories: [],
      filteredChildCategories: [],
      childCategories: [],
      
      // 自动编码相关
      autoCodeEnabled: false,
    }
  },
  created() {
    this.getList();
    this.loadCategoryData(); // 这将加载分类树并更新categoryOptions
    this.loadUnitOptions();
    // 不要同时加载，避免并发请求导致"数据正在处理"的错误
    // 使用setTimeout错开请求时间
    setTimeout(() => {
      this.loadParentCategories();
    }, 300);
    setTimeout(() => {
      this.loadChildCategories();
    }, 600);
  },
  
  mounted() {
    // 监听页面加载完成
    this.$nextTick(() => {
      console.log("组件加载完成，数据列表:", this.materialList);
    });
  },
  methods: {
    // 页码改变 - 直接处理pagination组件事件
    handleCurrentChange(val) {
      console.log("页码变更为:", val);
      this.queryParams.pageNum = Number(val);
      console.log("页码已更新为:", this.queryParams.pageNum);
      this.getList();
    },
    
    // 每页条数改变 - 直接处理pagination组件事件
    handleSizeChange(val) {
      console.log("每页条数变更为:", val);
      this.queryParams.pageSize = Number(val);
      this.queryParams.pageNum = 1; // 切换每页条数时重置为第一页
      console.log("每页条数已更新为:", this.queryParams.pageSize, "页码重置为:", this.queryParams.pageNum);
      this.getList();
    },
    
    // 保留兼容性
    currentChangeHandler(val) {
      this.handleCurrentChange(val);
    },

    // 保留兼容性
    sizeChangeHandler(val) {
      this.handleSizeChange(val);
    },

    // 根据ID查找分类（包括父分类和子分类）
    findCategoryById(categoryId) {
      if (!categoryId) return null;
      
      console.log(`尝试查找分类ID: ${categoryId}`);
      
      // 特殊处理：如果ID为1，可能对应"钢板类"(根据日志推断)
      if (categoryId === 1 || categoryId === "1") {
        console.log("发现ID为1的特殊情况，直接返回'钢板类'");
        return {
          material_classification_id: "1",
          material_classification_name: "钢板类",
          material_classification_code: "WLFL001"
        };
      }
      
      // 检查特殊格式的分类ID (例如 WLFL001, WLFLZ001)
      let isSpecialFormat = false;
      if (typeof categoryId === 'string' && (categoryId.startsWith('WLFL') || categoryId === 'WLFL001' || categoryId === 'WLFLZ001')) {
        isSpecialFormat = true;
        console.log(`检测到特殊格式的分类ID: ${categoryId}`);
      }
      
      // 在整个分类树中查找匹配的分类
      const findCategory = (nodes) => {
        if (!nodes || !Array.isArray(nodes)) return null;
        
        for (const node of nodes) {
          // 检查当前节点
          if (isSpecialFormat) {
            // 对于特殊格式的ID，匹配节点的分类编码或ID
            if (node.material_classification_code === categoryId || 
                node.material_subcategory_code === categoryId) {
              console.log(`找到特殊格式分类: ${node.material_classification_name || node.material_subcategory_name}`);
              return node;
            }
          } else {
            // 标准ID匹配 - 同时支持字符串和数字类型比较
            const nodeIds = [
              node.material_classification_id,
              node.id,
              node.material_subcategory_id
            ];
            
            // 将所有ID转换为字符串进行比较
            const categoryIdStr = String(categoryId);
            if (nodeIds.some(id => id !== undefined && String(id) === categoryIdStr)) {
              console.log(`找到标准格式分类: ${node.material_classification_name || node.material_subcategory_name}`);
              return node;
            }
          }
          
          // 递归检查子节点
          if (node.children && node.children.length > 0) {
            const found = findCategory(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      
      // 从根节点开始搜索整个分类树
      const result = findCategory(this.categoryTreeData);
      
      if (!result) {
        console.log(`未找到分类ID: ${categoryId}`);
      }
      
      return result;
    },
    
    // 获取物料列表
    getList(pagination) {
      // 直接打印原始pagination参数，便于调试
      console.log("原始分页事件参数:", JSON.stringify(pagination));
      
      // 更新queryParams中的分页参数
      if (pagination) {
        // 若依框架需要通过URL参数传递pageNum和pageSize
        this.queryParams.pageNum = Number(pagination.page);
        this.queryParams.pageSize = Number(pagination.limit);
        console.log("通过pagination事件更新分页参数: pageNum=" + this.queryParams.pageNum);
      }
      
      this.loading = true;
      
      console.log("请求前检查 - this.queryParams.pageNum =", this.queryParams.pageNum, 
                 "类型:", typeof this.queryParams.pageNum);
      
      // 防止出现NaN或者null/undefined
      if (!this.queryParams.pageNum || isNaN(this.queryParams.pageNum)) {
        this.queryParams.pageNum = 1;
      }
      if (!this.queryParams.pageSize || isNaN(this.queryParams.pageSize)) {
        this.queryParams.pageSize = 10;
      }
      
      // 克隆请求参数对象
      const params = JSON.parse(JSON.stringify(this.queryParams));
      
      console.log("当前分页状态 - 页码:", this.queryParams.pageNum, "每页条数:", this.queryParams.pageSize);
      console.log("发送查询参数:", JSON.stringify(params));
      
      // 调用API获取数据
      listMaterial(params).then(response => {
        console.log("API返回数据:", response);
        console.log("分页参数:", this.queryParams.pageNum, this.queryParams.pageSize);
        let dataSource = [];
        let totalCount = 0;
        
        // 判断数据来源 - 优先处理若依微服务框架的标准响应格式
        if (response && response.rows && Array.isArray(response.rows)) {
          // 若依微服务标准分页返回格式
          dataSource = response.rows;
          totalCount = response.total || 0;
          console.log("若依标准格式数据: rows=" + dataSource.length + ", total=" + totalCount);
        } else if (response && response.data && response.data.rows && Array.isArray(response.data.rows)) {
          // 嵌套的数据格式
          dataSource = response.data.rows;
          totalCount = response.data.total || 0;
          console.log("嵌套格式数据: rows=" + dataSource.length + ", total=" + totalCount);
        } else if (response.rows && response.rows.length > 0) {
          dataSource = response.rows;
        } else if (response.data && Array.isArray(response.data)) {
          dataSource = response.data;
        } else if (Array.isArray(response)) {
          dataSource = response;
        } else if (response.code === 200 && response.data) {
          if (Array.isArray(response.data)) {
            dataSource = response.data;
          } else {
            dataSource = [response.data];
          }
        }
        
        console.log("处理后数据源:", dataSource);
        
        // 处理数据
        if (dataSource && dataSource.length > 0) {
          this.materialList = dataSource.map((item, index) => {
            // 打印每个字段，帮助调试
            console.log("数据项:", item);
            
            // 转换物料类型代码为文字描述
            let materialTypeText = '';
            const typeCode = item.material_type || item.materialType || item.material_mp;
            if (typeCode === '1' || typeCode === 1) {
              materialTypeText = '生产物料';
            } else if (typeCode === '2' || typeCode === 2) {
              materialTypeText = '半成品';
            } else if (typeCode === '3' || typeCode === 3) {
              materialTypeText = '其他';
            } else {
              materialTypeText = typeCode || '';
            }
            
            // 确保页码计算正确
            const currentPage = parseInt(this.queryParams.pageNum) || 1;
            const pageSize = parseInt(this.queryParams.pageSize) || 10;
            
            // 获取正确的分类名称
            let categoryName = '';
            
            // 根据截图中的数据结构，直接从item.material_fl获取分类名称
            if (item.material_fl) {
              categoryName = item.material_fl;
              console.log(`从API直接获取物料[${item.material_code || item.materialCode}]的分类名称: ${categoryName}`);
            } else {
              // 尝试从多个可能的ID字段查找分类
              const categoryId = item.material_classification_id;
              const subcategoryId = item.material_subcategory_id;
              
              // 先检查是否有子分类ID
              if (subcategoryId) {
                // 从分类树中查找子分类信息
                const subcategoryInfo = this.findCategoryById(subcategoryId);
                if (subcategoryInfo) {
                  categoryName = subcategoryInfo.material_classification_name || subcategoryInfo.material_subcategory_name;
                  console.log(`从分类树中找到物料[${item.material_code || item.materialCode}]的子分类: ${categoryName}`);
                }
              }
              
              // 如果没有找到子分类，尝试查找父分类
              if (!categoryName && categoryId) {
                const categoryInfo = this.findCategoryById(categoryId);
                if (categoryInfo) {
                  categoryName = categoryInfo.material_classification_name;
                  console.log(`从分类树中找到物料[${item.material_code || item.materialCode}]的父分类: ${categoryName}`);
                }
              }
              
              // 如果仍然没有找到，使用API返回的其他可能的值
              if (!categoryName) {
                categoryName = item.material_classification_name || item.material_category || item.materialCategory || item.category_name || '';
                if (categoryName) {
                  console.log(`使用API返回的分类名称: ${categoryName}`);
                } else {
                  console.log(`未找到物料[${item.material_code || item.materialCode}]的分类信息`);
                }
              }
            }
            
            // 如果仍然没有分类名称，尝试从其他可能的字段获取
            if (!categoryName) {
              categoryName = item.material_classification_name || item.material_category || item.materialCategory || item.category_name || '';
            }
            
            // 确保正确获取物料ID
            const materialId = item.material_id !== undefined ? item.material_id : (item.id !== undefined ? item.id : null);
            console.log(`物料[${item.material_code || item.materialCode}]的ID:`, materialId);
            
            // 确定状态值 - 更全面的状态判断
            let statusValue;
            // 检查material_status字段
            if (item.material_status === '1' || item.material_status === 1) {
              statusValue = '启用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(material_status): 启用`);
            } else if (item.material_status === '0' || item.material_status === 0) {
              statusValue = '停用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(material_status): 停用`);
            } 
            // 检查status字段
            else if (item.status === '1' || item.status === 1) {
              statusValue = '启用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(status): 启用`);
            } else if (item.status === '0' || item.status === 0) {
              statusValue = '停用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(status): 停用`);
            }
            // 检查status是否直接是文本值
            else if (item.status === '启用') {
              statusValue = '启用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(直接文本): 启用`);
            } else if (item.status === '停用') {
              statusValue = '停用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(直接文本): 停用`);
            }
            // 检查其他可能的状态字段
            else if (item.material_state === '1' || item.material_state === 1 || item.state === '1' || item.state === 1) {
              statusValue = '启用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(其他字段): 启用`);
            } else if (item.material_state === '0' || item.material_state === 0 || item.state === '0' || item.state === 0) {
              statusValue = '停用';
              console.log(`物料[${item.material_code || item.materialCode}]状态(其他字段): 停用`);
            } else {
              // 默认值
              statusValue = '启用';
              console.log(`物料[${item.material_code || item.materialCode}]无法确定状态，使用默认值: 启用`);
            }
            
            return {
              index: (currentPage - 1) * pageSize + index + 1,
              id: materialId, // 使用解析后的物料ID
              material_id: materialId, // 同时保存material_id字段
              materialCode: item.material_code || item.materialCode || item.gc001 || '',
              materialName: item.material_name || item.materialName || '',
              specification: item.spec || item.specification || item.material_sfn || '',
              unit: item.unit || item.material_unit || '',
              materialType: materialTypeText,
              materialTypeValue: typeCode, // 保存原始值
              materialAttr: this.getMaterialAttrText(item.material_mp) || '',
              materialCategory: categoryName || item.material_fl || item.wlfl || item.materialFl || 
                               item.materialCategory || item.material_category || item.categoryName || '',
              status: statusValue, // 使用处理后的状态值
              material_status: statusValue === '启用' ? '1' : '0', // 添加数字状态值
              createTime: item.create_time || item.createTime || '',
              createBy: item.create_by || item.createBy || '',
              categoryId: item.material_classification_id, // 保存分类ID
              subcategoryId: item.material_subcategory_id, // 保存子分类ID
              rawData: item // 保存原始数据以备编辑时使用
            };
          });
          
          console.log("处理后的表格数据:", this.materialList);
          
          // 主动查询物料分类信息并更新表格数据
          this.fetchMaterialCategories();
        } else {
          console.warn("无法从API响应中提取数据");
          this.materialList = [];
        }
        
        // 确保从API响应中正确提取总记录数 - 若依微服务标准格式
        if (totalCount > 0) {
          // 优先使用前面解析的totalCount
          this.total = totalCount;
        } else if (response.total !== undefined) {
          this.total = response.total;
        } else if (response.data && response.data.total !== undefined) {
          this.total = response.data.total;
        } else if (response.count !== undefined) {
          this.total = response.count;
        } else {
          this.total = dataSource.length || 0;
        }
        console.log("总记录数:", this.total);
        this.loading = false;
      }).catch(error => {
        console.error("获取物料列表失败", error);
        this.loading = false;
        this.materialList = [];
        this.total = 0;
      });
    },
    
    // 新增方法: 获取物料分类信息并更新表格数据
    fetchMaterialCategories() {
      // 检查是否有需要查询分类的物料
      const materialsNeedCategory = this.materialList.filter(item => 
        !item.materialCategory && (item.categoryId || item.subcategoryId));
      
      if (materialsNeedCategory.length === 0) {
        console.log("没有需要查询分类的物料");
        return;
      }
      
      console.log(`发现${materialsNeedCategory.length}个物料需要查询分类信息`);
      
      // 首先确保分类树已加载
      if (!this.categoryTreeData || this.categoryTreeData.length === 0 || 
          (this.categoryTreeData.length === 1 && !this.categoryTreeData[0].children)) {
        console.log("分类树数据未加载，先加载分类树");
        this.loadCategoryData().then(() => {
          this.updateMaterialCategories(materialsNeedCategory);
        });
      } else {
        this.updateMaterialCategories(materialsNeedCategory);
      }
    },
    
    // 更新物料分类信息
    updateMaterialCategories(materials) {
      if (!materials || materials.length === 0) return;
      
      console.log("开始更新物料分类信息");
      
      // 定义常见的分类ID映射，确保即使分类树未加载也能显示常见分类
      const commonCategories = {
        "1": "钢板类",
        "2": "型材类",
        "3": "管材类",
        "4": "其他钢材",
        "5": "原料类",
        "WLFL001": "钢板类",
        "WLFLZ001": "中厚板"
      };
      
      // 遍历需要更新分类的物料
      materials.forEach(material => {
        // 使用物料的分类ID查找分类名称
        let categoryName = '';
        
        // 先尝试从映射表中获取常见分类名称
        if (material.categoryId && commonCategories[material.categoryId]) {
          categoryName = commonCategories[material.categoryId];
          console.log(`从常见分类映射中获取物料[${material.materialCode}]的分类名称: ${categoryName}`);
        } else if (material.subcategoryId && commonCategories[material.subcategoryId]) {
          categoryName = commonCategories[material.subcategoryId];
          console.log(`从常见分类映射中获取物料[${material.materialCode}]的分类名称: ${categoryName}`);
        }
        
        // 如果映射表中没有，再从分类树中查找
        if (!categoryName) {
          // 先检查是否有子分类ID
          if (material.subcategoryId) {
            const subcategory = this.findCategoryById(material.subcategoryId);
            if (subcategory) {
              categoryName = subcategory.material_classification_name || subcategory.material_subcategory_name;
              console.log(`为物料[${material.materialCode}]找到子分类: ${categoryName}`);
            }
          }
          
          // 如果没找到子分类，尝试查找父分类
          if (!categoryName && material.categoryId) {
            const category = this.findCategoryById(material.categoryId);
            if (category) {
              categoryName = category.material_classification_name;
              console.log(`为物料[${material.materialCode}]找到父分类: ${categoryName}`);
            }
          }
        }
        
        // 如果找到了分类名称，更新物料数据
        if (categoryName) {
          // 找到物料在列表中的索引
          const index = this.materialList.findIndex(item => item.id === material.id);
          if (index !== -1) {
            // 更新物料的分类名称
            this.$set(this.materialList[index], 'materialCategory', categoryName);
            console.log(`已更新物料[${material.materialCode}]的分类为: ${categoryName}`);
          }
        }
      });
      
      // 强制更新视图
      this.$forceUpdate();
    },
    
    // 备用方法：使用静态数据或跳过子分类加载
    useFallbackCategoryData() {
      console.log("使用备用方法加载分类数据");
      
      // 静态数据 - 当API失败时使用
      const staticParentCategories = [
        {
          material_classification_id: '1001',
          material_classification_code: 'FL001',
          material_classification_name: '原材料'
        },
        {
          material_classification_id: '1002',
          material_classification_code: 'FL002',
          material_classification_name: '半成品'
        },
        {
          material_classification_id: '1003',
          material_classification_code: 'FL003',
          material_classification_name: '成品'
        },
        {
          material_classification_id: '1004',
          material_classification_code: 'FL004',
          material_classification_name: '辅料'
        }
      ];
      
      const staticChildCategories = [
        {
          material_subcategory_id: '2001',
          material_subcategory_code: 'ZFL001',
          material_subcategory_name: '金属材料',
          parent_id: '1001'
        },
        {
          material_subcategory_id: '2002',
          material_subcategory_code: 'ZFL002',
          material_subcategory_name: '塑料材料',
          parent_id: '1001'
        },
        {
          material_subcategory_id: '2003',
          material_subcategory_code: 'ZFL003',
          material_subcategory_name: '电子元件',
          parent_id: '1001'
        },
        {
          material_subcategory_id: '2004',
          material_subcategory_code: 'ZFL004',
          material_subcategory_name: '机械零件',
          parent_id: '1002'
        },
        {
          material_subcategory_id: '2005',
          material_subcategory_code: 'ZFL005',
          material_subcategory_name: '电路板',
          parent_id: '1002'
        },
        {
          material_subcategory_id: '2006',
          material_subcategory_code: 'ZFL006',
          material_subcategory_name: '包装材料',
          parent_id: '1004'
        }
      ];
      
      // 检查是否已经有父分类数据
      if (!this.parentCategories || this.parentCategories.length === 0) {
        this.parentCategories = staticParentCategories;
      }
      
      // 检查是否已经有子分类数据
      if (!this.childCategories || this.childCategories.length === 0) {
        this.childCategories = staticChildCategories;
      }
      
      // 构建分类树
      const rootNode = {
        id: '0',
        material_classification_id: '0',
        material_classification_name: '全部物料',
        children: []
      };
      
      // 处理父分类
      const processedParents = this.parentCategories.map(item => {
        return {
          id: item.material_classification_id,
          material_classification_id: item.material_classification_id,
          material_classification_code: item.material_classification_code,
          material_classification_name: item.material_classification_name,
          children: []
        };
      });
      
      // 设置分类树
      this.categoryTreeData = [rootNode];
      rootNode.children = processedParents;
      
      // 分配子分类到父分类
      this.assignSubcategoriesToParents(this.childCategories);
      
      // 更新级联选择器选项
      this.updateCategoryOptions();
      
      // 强制Vue更新视图
      this.$forceUpdate();
      
      // 完成加载
      this.treeLoading = false;
    },
    
    // 加载物料分类数据
    loadCategoryData() {
      // 显示加载状态
      this.treeLoading = true;
      
      // 返回Promise以支持异步流程
      return new Promise((resolve, reject) => {
        // 设置超时处理，确保不会一直显示加载中
        const loadingTimeout = setTimeout(() => {
          if (this.treeLoading) {
            console.log("物料分类加载超时，使用备用数据");
            this.useFallbackCategoryData();
            resolve(); // 使用备用数据后也要解析Promise
          }
        }, 5000); // 5秒超时
        
        // 首先加载父分类
        listAllParentCategories().then(response => {
          // 清除超时计时器
          clearTimeout(loadingTimeout);
          
          console.log("父分类数据原始结构:", response);
          
          // 解析返回数据，兼容多种可能的数据结构
          let parentCategories = [];
          if (response && response.code === 200) {
            parentCategories = response.data || response.rows || [];
          } else if (response && response.rows && Array.isArray(response.rows)) {
            parentCategories = response.rows;
          } else if (response && response.data && Array.isArray(response.data)) {
            parentCategories = response.data;
          } else if (Array.isArray(response)) {
            parentCategories = response;
          }
          
          console.log("提取的父分类数据:", parentCategories);
          
          if (parentCategories.length > 0) {
            // 创建包含"全部物料"的根节点
            const rootNode = {
              id: '0',
              material_classification_id: '0',
              material_classification_name: '全部物料',
              children: []
            };
            
            // 将API返回的分类作为子节点，并处理属性
            const processedParents = parentCategories.map(item => {
              // 添加必要的属性
              const parent = {
                id: item.material_classification_id || item.id,
                material_classification_id: item.material_classification_id || item.id,
                material_classification_code: item.material_classification_code || item.code,
                material_classification_name: item.material_classification_name || 
                                           item.material_classification_code || 
                                           item.name || '未命名分类',
                children: []
              };
              
              // 调试输出每个父分类项
              console.log("处理父分类:", parent.material_classification_code, parent.material_classification_name);
              return parent;
            });
            
            // 设置父分类
            this.categoryTreeData = [rootNode];
            rootNode.children = processedParents;
            
            // 强制Vue更新视图
            this.$forceUpdate();
            
            // 更新级联选择器选项
            this.updateCategoryOptions();
            
            // 保存到parentCategories，以便在弹窗中使用
            this.parentCategories = processedParents;
            
            // 加载完父分类后，延迟一段时间再加载子分类，避免并发请求
            setTimeout(() => {
              this.loadAllSubcategoriesAtOnce().then(() => {
                resolve(); // 全部加载完成后解析Promise
              }).catch(err => {
                console.error("加载子分类失败", err);
                resolve(); // 即使失败也解析Promise
              });
            }, 300);
            
            console.log("处理后的分类树结构:", JSON.stringify(this.categoryTreeData));
          } else {
            console.warn("未找到父分类数据，使用备用数据");
            // 使用备用数据
            this.useFallbackCategoryData();
            resolve(); // 使用备用数据后解析Promise
          }
        }).catch(error => {
          console.error("获取物料分类失败", error);
          // 使用备用数据
          this.useFallbackCategoryData();
          
          // 清除超时计时器
          clearTimeout(loadingTimeout);
          
          // 即使失败也解析Promise
          resolve();
        });
      });
    },
    
    // 加载父分类列表
    loadParentCategories() {
      // 如果已经加载过父分类，不重复加载
      if (this.parentCategories && this.parentCategories.length > 0) {
        console.log("父分类已加载，跳过重复加载");
        return;
      }
      
      listAllParentCategories().then(response => {
        if (response && response.code === 200) {
          this.parentCategories = response.data || response.rows || [];
          console.log("加载父分类成功:", this.parentCategories);
        } else {
          this.parentCategories = [];
          console.warn("加载父分类失败或无数据");
        }
      }).catch(error => {
        console.error("加载父分类失败", error);
        this.parentCategories = [];
      });
    },

    // 加载所有子分类
    loadChildCategories() {
      // 如果已经加载过子分类，不重复加载
      if (this.childCategories && this.childCategories.length > 0) {
        console.log("子分类已加载，跳过重复加载");
        return;
      }
      
      try {
        const queryParams = {};
        
        // 使用Promise.resolve来避免直接调用API可能导致的错误
        Promise.resolve()
          .then(() => {
            // 尝试加载子分类数据
            return listMaterialCategory(queryParams);
          })
          .then(response => {
            if (response && response.code === 200) {
              // 处理多种可能的数据结构
              let childData = [];
              if (response.data && Array.isArray(response.data)) {
                childData = response.data;
              } else if (response.rows && Array.isArray(response.rows)) {
                childData = response.rows;
              } else if (Array.isArray(response)) {
                childData = response;
              }
              
              this.childCategories = childData.map(item => {
                // 确保数据结构一致
                return {
                  material_subcategory_id: item.material_subcategory_id || item.id,
                  material_subcategory_name: item.material_subcategory_name || item.name || '未命名子分类',
                  material_subcategory_code: item.material_subcategory_code || item.code || '',
                  parent_id: item.parent_id || item.material_classification_id,
                  material_classification_id: item.material_classification_id || item.parent_id
                };
              });
              
              console.log("加载所有子分类成功:", this.childCategories);
              
              // 如果已选择父分类，更新过滤后的子分类
              if (this.selectedParentId) {
                this.filterChildCategories();
              }
            } else {
              this.childCategories = [];
              console.warn("加载所有子分类失败或无数据");
              
              // 尝试使用备用方法加载
              setTimeout(() => {
                this.loadChildCategoriesFallback();
              }, 500);
            }
          })
          .catch(error => {
            console.error("加载所有子分类失败", error);
            this.childCategories = [];
            
            // 尝试使用备用方法加载
            setTimeout(() => {
              this.loadChildCategoriesFallback();
            }, 500);
          });
      } catch (error) {
        console.error("调用子分类加载方法时发生异常:", error);
        this.childCategories = [];
        
        // 尝试使用备用方法加载
        setTimeout(() => {
          this.loadChildCategoriesFallback();
        }, 500);
      }
    },
    
    // 一次性加载所有子分类并分配到对应的父分类下
    loadAllSubcategoriesAtOnce() {
      // 返回Promise以支持异步流程
      return new Promise((resolve, reject) => {
        // 设置超时处理，确保不会一直显示加载中
        const loadingTimeout = setTimeout(() => {
          if (this.treeLoading) {
            console.log("子分类加载超时，使用已有数据");
            // 即使没有子分类数据，也关闭加载状态
            this.treeLoading = false;
            resolve(); // 超时后解析Promise
          }
        }, 5000); // 5秒超时
        
        // 如果已经加载过子分类，不重复加载
        if (this.childCategories && this.childCategories.length > 0) {
          console.log("子分类已加载，跳过重复加载");
          this.assignSubcategoriesToParents(this.childCategories);
          this.treeLoading = false;
          clearTimeout(loadingTimeout);
          resolve(); // 已有数据，直接解析Promise
          return;
        }
        
        // 构建查询参数
        const queryParams = {};
        
        console.log("查询所有子分类的参数:", queryParams);
        this.treeLoading = true;
        
        // 使用try-catch包裹整个API调用过程
        try {
          // 查询所有子分类
          listMaterialCategory(queryParams)
            .then(response => {
              console.log("所有子分类API返回数据:", response);
              
              // 解析返回数据，兼容多种可能的数据结构
              let childData = [];
              if (response && response.code === 200) {
                childData = response.data || response.rows || [];
              } else if (response && response.rows && Array.isArray(response.rows)) {
                childData = response.rows;
              } else if (response && response.data && Array.isArray(response.data)) {
                childData = response.data;
              } else if (Array.isArray(response)) {
                childData = response;
              }
              
              console.log("提取的所有子分类数据:", childData);
              
              // 提取所有子分类数据，处理可能的嵌套结构
              let allSubcategories = [];
              
              childData.forEach(item => {
                // 处理直接的子分类
                if (item.material_subcategory_id) {
                  // 确保子分类数据完整
                  if (!item.material_subcategory_name && item.name) {
                    item.material_subcategory_name = item.name;
                  }
                  if (!item.material_subcategory_code && item.code) {
                    item.material_subcategory_code = item.code;
                  }
                      
                  // 确保有父ID
                  if (!item.parent_id && item.material_classification_id) {
                    console.log(`子分类 ${item.material_subcategory_name} 使用material_classification_id作为父ID`);
                    item.parent_id = item.material_classification_id;
                  }
                  
                  allSubcategories.push(item);
                }
                
                // 处理可能的嵌套子分类
                if (item.basicWlflz && Array.isArray(item.basicWlflz)) {
                  // 处理嵌套子分类中的每一项，确保数据完整
                  const processedSubcategories = item.basicWlflz.map(subItem => {
                    // 确保子分类数据完整
                    if (!subItem.material_subcategory_name && subItem.name) {
                      subItem.material_subcategory_name = subItem.name;
                    }
                    if (!subItem.material_subcategory_code && subItem.code) {
                      subItem.material_subcategory_code = subItem.code;
                    }
                        
                    // 确保有父ID - 使用当前item的ID作为父ID
                    if (!subItem.parent_id && item.material_classification_id) {
                      subItem.parent_id = item.material_classification_id;
                      console.log(`为嵌套子分类 ${subItem.material_subcategory_name} 设置父ID: ${subItem.parent_id}`);
                    }
                    
                    return subItem;
                  });
                  allSubcategories = allSubcategories.concat(processedSubcategories);
                }
                    
                // 处理第二种可能的嵌套结构 - 有些后端可能使用children字段
                if (item.children && Array.isArray(item.children)) {
                  const childrenSubcategories = item.children.map(child => {
                    // 确保子分类数据完整
                    if (!child.material_subcategory_id && child.id) {
                      child.material_subcategory_id = child.id;
                    }
                    if (!child.material_subcategory_name && child.name) {
                      child.material_subcategory_name = child.name || child.material_classification_name;
                    }
                    if (!child.material_subcategory_code && child.code) {
                      child.material_subcategory_code = child.code || child.material_classification_code;
                    }
                    
                    // 设置父ID
                    if (!child.parent_id && item.material_classification_id) {
                      child.parent_id = item.material_classification_id;
                    }
                    
                    return child;
                  });
                  allSubcategories = allSubcategories.concat(childrenSubcategories);
                }
              });
              
              console.log("处理后的所有子分类数据:", allSubcategories);
                  
              // 保存到childCategories数组，以便在弹窗中使用
              this.childCategories = allSubcategories.map(item => {
                return {
                  material_subcategory_id: item.material_subcategory_id || item.id,
                  material_subcategory_name: item.material_subcategory_name || item.name || '未命名子分类',
                  material_subcategory_code: item.material_subcategory_code || item.code || '',
                  parent_id: item.parent_id || item.material_classification_id,
                  material_classification_id: item.material_classification_id || item.parent_id
                };
              });
              
              if (allSubcategories.length > 0) {
                // 将子分类添加到对应的父分类下
                this.assignSubcategoriesToParents(allSubcategories);
              } else {
                // 如果没有子分类数据，使用备用数据
                console.warn("未找到子分类数据，使用备用数据");
                this.useFallbackCategoryData();
              }
              
              this.treeLoading = false;
              
              // 更新级联选择器选项
              this.updateCategoryOptions();
              
              // 强制Vue更新视图
              this.$forceUpdate();
              
              // 打印最终的分类树结构
              console.log("所有子分类加载完成，最终的分类树结构:", 
                JSON.parse(JSON.stringify(this.categoryTreeData)));
              
              // 调试输出树结构
              this.debugCategoryTree();
                  
              // 清除超时计时器
              clearTimeout(loadingTimeout);
              
              // 解析Promise
              resolve();
            })
            .catch(error => {
              console.error("获取所有子分类失败", error);
                  
              // 使用备用方法或静态数据
              setTimeout(() => {
                this.useFallbackCategoryData();
                // 解析Promise
                resolve();
              }, 500);
                  
              this.treeLoading = false;
                  
              // 清除超时计时器
              clearTimeout(loadingTimeout);
            });
        } catch (error) {
          console.error("调用子分类API时发生异常:", error);
          
          // 使用备用方法或静态数据
          setTimeout(() => {
            this.useFallbackCategoryData();
            // 解析Promise
            resolve();
          }, 500);
          
          this.treeLoading = false;
          
          // 清除超时计时器
          clearTimeout(loadingTimeout);
          
          // 拒绝Promise
          reject(error);
        }
      });
    },
    
    // 将子分类分配给对应的父分类
    assignSubcategoriesToParents(subcategories) {
      if (!subcategories || subcategories.length === 0) return;
      
      // 获取所有父分类（除了根节点"全部物料"）
      const parentCategories = this.categoryTreeData[0].children;
      if (!parentCategories || parentCategories.length === 0) return;
      
      console.log("开始分配子分类到父分类...");
      
      // 遍历所有子分类
      subcategories.forEach(child => {
        if (!child) return;
        
        // 子分类中的父ID可能是parent_id或material_classification_id字段
        const parentId = child.parent_id || child.material_classification_id;
        if (!parentId) {
          console.log("子分类缺少父ID:", child);
          return;
        }
        
        // 查找对应的父分类
        const parentIndex = parentCategories.findIndex(p => 
          p.material_classification_id === parentId || 
          p.id === parentId
        );
        
        if (parentIndex !== -1) {
          if (!parentCategories[parentIndex].children) {
            parentCategories[parentIndex].children = [];
          }
          
          // 检查子分类是否已存在
          const existingChildIndex = parentCategories[parentIndex].children.findIndex(
            c => c.material_subcategory_id === child.material_subcategory_id || 
                c.id === child.material_subcategory_id
          );
          
          if (existingChildIndex !== -1) {
            console.log(`子分类 ${child.material_subcategory_name || child.name} 已存在，跳过`);
            return;
          }
          
          // 将子分类添加到父分类的children数组中
          const childNode = {
            id: child.material_subcategory_id || child.id,
            material_classification_id: child.material_classification_id || parentId,
            material_subcategory_id: child.material_subcategory_id || child.id,
            material_classification_code: child.material_subcategory_code || child.code,
            material_classification_name: child.material_subcategory_name || child.name || '未命名子分类',
            material_subcategory_name: child.material_subcategory_name || child.name || '未命名子分类',
            material_subcategory_code: child.material_subcategory_code || child.code,
            createTime: child.create_time,
            createBy: child.create_by,
            parentId: parentId,
            isSubcategory: true, // 标记为子分类
            leaf: true // 标记为叶子节点
          };
          
          parentCategories[parentIndex].children.push(childNode);
          
          console.log(`将子分类 ${childNode.material_classification_name} (ID: ${childNode.material_subcategory_id}) 添加到父分类 ${parentCategories[parentIndex].material_classification_name} 下`);
          
          // 同时更新childCategories数组，确保弹窗中可以显示
          if (!this.childCategories.some(c => c.material_subcategory_id === childNode.material_subcategory_id)) {
            this.childCategories.push({
              material_subcategory_id: childNode.material_subcategory_id,
              material_subcategory_name: childNode.material_subcategory_name,
              material_subcategory_code: childNode.material_subcategory_code,
              parent_id: parentId
            });
          }
        } else {
          console.log(`未找到ID为 ${parentId} 的父分类，无法添加子分类:`, child);
        }
      });
      
      // 确保所有父分类都有children属性，即使为空数组
      parentCategories.forEach(parent => {
        if (!parent.children) {
          parent.children = [];
        }
      });
      
      console.log("子分类分配完成，更新后的父分类:", parentCategories);
      console.log("childCategories数组更新为:", this.childCategories);
    },
    
    // 加载子分类 - 保留此方法以兼容其他地方可能的调用
    loadSubcategories(parentNode) {
      console.log("调用了loadSubcategories方法，父分类:", parentNode.material_classification_name, "ID:", parentNode.material_classification_id);
      // 如果已经加载过子分类，不重复加载
      if (parentNode.children && parentNode.children.length > 0) {
        console.log("已有子分类数据，不重复加载");
        return;
      }
      
      // 使用父分类ID作为查询条件
      const queryParams = {
        parentId: parentNode.material_classification_id
      };
      
      console.log("查询子分类的参数:", queryParams);
      
      try {
        // 使用Promise.resolve来避免直接调用API可能导致的错误
        Promise.resolve()
          .then(() => {
            // 尝试加载子分类数据
            return listMaterialCategory(queryParams);
          })
          .then(response => {
          console.log("子分类API返回数据:", response);
          
          // 解析返回数据，兼容多种可能的数据结构
          let subcategoryData = [];
          if (response && response.code === 200) {
            subcategoryData = response.data || response.rows || [];
          } else if (response && response.rows && Array.isArray(response.rows)) {
            subcategoryData = response.rows;
          } else if (response && response.data && Array.isArray(response.data)) {
            subcategoryData = response.data;
          } else if (Array.isArray(response)) {
            subcategoryData = response;
          }
          
          console.log("提取的子分类数据:", subcategoryData);
          
          if (subcategoryData && subcategoryData.length > 0) {
            // 处理子分类数据
            const subcategories = subcategoryData.map(item => {
              return {
                id: item.material_subcategory_id || item.id,
                material_classification_id: item.material_subcategory_id || item.id,
                material_classification_code: item.material_subcategory_code || item.code,
                material_classification_name: item.material_subcategory_name || 
                                           item.name || 
                                           item.material_subcategory_code || 
                                           '未命名',
                parentId: parentNode.material_classification_id,
                parentCode: parentNode.material_classification_code
              };
            });
            
            console.log("处理后的子分类数组:", subcategories);
            
            // 设置父节点的子节点
            this.$set(parentNode, 'children', subcategories);
            // 更新级联选择器选项
            this.updateCategoryOptions();
            // 强制Vue更新视图
            this.$forceUpdate();
          } else {
            console.log("未找到子分类数据");
            // 没有子分类，设置空数组
            this.$set(parentNode, 'children', []);
        }
          })
          .catch(error => {
          console.error("获取子分类失败", error);
          // 发生错误时设置空子分类
          this.$set(parentNode, 'children', []);
        });
      } catch (err) {
        console.error("调用子分类API时出错:", err);
        this.$set(parentNode, 'children', []);
      }
    },
    
    // 物料分类树节点点击
    handleCategoryClick(data) {
      console.log("点击的分类:", data);
      
      if (data.id === '0') {
        // 点击"全部物料"时清空分类ID过滤
        this.queryParams.categoryId = undefined;
        this.queryParams.material_fl = undefined;
        this.queryParams.material_classification_id = undefined;
        this.queryParams.material_subcategory_id = undefined;
        // 清除嵌套对象参数
        this.queryParams.basicWlfl = undefined;
        this.queryParams.basicWlflz = undefined;
      } else {
        // 确定是父分类还是子分类
        // 根据您的截图，子分类有isSubcategory=true标记
        const isSubcategory = !!data.material_subcategory_id || !!data.parentId || data.isSubcategory === true;
        
        // 获取正确的分类ID
        let categoryId;
        if (isSubcategory) {
          // 如果是子分类，使用子分类ID
          categoryId = data.material_subcategory_id || data.id;
          console.log("选中的是子分类，使用子分类ID:", categoryId);
          
          // 根据SQL查询结构设置参数
          this.queryParams.material_subcategory_id = categoryId;
          // 清除父分类ID参数
          delete this.queryParams.material_classification_id;
          
          // 设置嵌套对象参数，匹配SQL查询中的条件
          this.queryParams.basicWlflz = {
            material_subcategory_id: categoryId
          };
          delete this.queryParams.basicWlfl;
          
          console.log("设置子分类查询参数 basicWlflz.material_subcategory_id =", categoryId);
        } else {
          // 如果是父分类，使用父分类ID
          categoryId = data.material_classification_id || data.id;
          console.log("选中的是父分类，使用父分类ID:", categoryId);
          
          // 根据SQL查询结构设置参数
          this.queryParams.material_classification_id = categoryId;
          // 清除子分类ID参数
          delete this.queryParams.material_subcategory_id;
          
          // 设置嵌套对象参数，匹配SQL查询中的条件
          this.queryParams.basicWlfl = {
            material_classification_id: categoryId
          };
          delete this.queryParams.basicWlflz;
          
          console.log("设置父分类查询参数 basicWlfl.material_classification_id =", categoryId);
        }
        
        // 设置通用categoryId参数
        this.queryParams.categoryId = categoryId;
        
        // 设置分类名称，用于显示
        this.queryParams.material_fl = data.material_classification_name || data.material_subcategory_name;
        
        // 打印完整的分类信息，帮助调试
        console.log("选中的分类信息:", {
          id: data.id,
          material_classification_id: data.material_classification_id,
          material_subcategory_id: data.material_subcategory_id,
          material_classification_code: data.material_classification_code || data.material_subcategory_code,
          material_classification_name: data.material_classification_name || data.material_subcategory_name,
          parentId: data.parentId,
          isSubcategory: isSubcategory
        });
        
        console.log("设置的查询参数:", {
          categoryId: this.queryParams.categoryId,
          material_classification_id: this.queryParams.material_classification_id,
          material_subcategory_id: this.queryParams.material_subcategory_id,
          material_fl: this.queryParams.material_fl,
          basicWlfl: this.queryParams.basicWlfl,
          basicWlflz: this.queryParams.basicWlflz
        });
      }
      
      // 切换分类时重置到第一页
      this.queryParams.pageNum = 1;
      console.log("分类切换 - 重置页码为:", this.queryParams.pageNum, "分类ID:", this.queryParams.categoryId);
      
      // 查询符合条件的物料
      this.$nextTick(() => {
        this.getList();
      });
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    
    // 搜索按钮操作
    handleQuery() {
      // 构建API所需查询参数
      if (this.queryParams.keyword) {
        // 根据SQL查询中的 wl.material_name like CONCAT('%',#{material_name},'%')
        // 设置正确的参数名
        this.queryParams.material_name = this.queryParams.keyword;
        
        console.log("设置模糊查询参数 - 物料名称:", this.queryParams.keyword);
      } else {
        // 清除之前的搜索条件
        delete this.queryParams.material_name;
      }
      
      // 处理物料类型查询参数
      if (this.queryParams.materialType) {
        // 将前端的materialType映射到后端的material_type参数
        this.queryParams.material_type = this.queryParams.materialType;
        console.log("设置物料类型查询参数:", this.queryParams.material_type);
      } else {
        // 清除物料类型查询条件
        delete this.queryParams.material_type;
      }
      
      // 处理单位查询参数
      if (this.queryParams.unit) {
        // 将前端的unit映射到后端的material_unit参数
        this.queryParams.material_unit = this.queryParams.unit;
        console.log("设置单位查询参数:", this.queryParams.material_unit);
      } else {
        // 清除单位查询条件
        delete this.queryParams.material_unit;
      }
      
      // 搜索时重置到第一页
      this.queryParams.pageNum = 1;
      console.log("搜索操作 - 重置页码为:", this.queryParams.pageNum);
      this.getList();
    },
    
    // 重置按钮操作
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,
        materialName: undefined,
        material_name: undefined,  // 添加后端参数
        materialType: undefined,
        material_type: undefined,  // 添加后端参数
        // 移除了单位相关参数
        categoryId: undefined,
        material_classification_id: undefined,
        material_subcategory_id: undefined, // 添加子分类ID
        material_fl: undefined,
        keyword: undefined
      };
      console.log("重置操作 - 重置页码为:", this.queryParams.pageNum, "每页条数:", this.queryParams.pageSize);
      this.getList();
    },
    
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        materialCode: '',         // 物料编号
        materialName: '',         // 物料名称
        specification: '',        // 规格型号 (material_sfn)
        unit: '',                 // 单位 (material_unit)
        materialType: '',         // 物料类型 (material_mp)
        materialAttr: '',         // 物料属性
        materialCategory: '',     // 物料分类 (material_fl)
        categoryId: [],           // 分类ID
        status: '停用',           // 状态
        remark: '',               // 备注
        // 后端需要的字段
        material_code: '',
        material_name: '',
        material_sfn: '',
        material_unit: '',        // 确保单位值字段存在
        material_mp: '',
        material_fl: '',
        material_type: '',        // 物料类型
        material_status: '0'      // 状态，默认为停用(0)
      };
      this.resetForm("form");
      this.selectedParentId = null;
      this.selectedChildId = null;
      this.filteredChildCategories = [];
      
      // 重置自动编码状态
      this.autoCodeEnabled = false;
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    
    // 表单提交
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 如果开启了自动编号，在提交前获取真正的编号
          if (!this.form.id && this.form.materialCode) {
            try {
              const response = await getAutoNumbersConsume(16);
              if (typeof response === 'string') {
                this.form.materialCode = response;
              } else if (response && response.msg) {
                this.form.materialCode = response.msg;
              }
            } catch (error) {
              this.$message.error('获取最终物料编号失败');
              return;
            }
          }
          
          // 添加调试日志，帮助排查问题
          console.log("提交表单数据:", this.form);
          
          // 将表单数据映射为后端需要的格式
          const submitData = {
            id: this.form.id,
            material_id: this.form.id, // 确保正确映射material_id字段
            material_code: this.form.materialCode,
            material_name: this.form.materialName,
            material_sfn: this.form.specification,
            material_unit: this.form.unit,  // 确保单位值正确传递
            material_type: this.form.materialType,  // 物料类型代码
            material_mp: this.form.materialAttr,    // 物料属性
            status: this.form.status === '启用' ? '1' : '0',
            material_status: this.form.status === '启用' ? '1' : '0', // 添加material_status字段
            remark: this.form.remark
          };
          
          // 调试日志
          console.log("提交到后端的数据:", submitData);
          
          // 打印单位值，确保正确传递
          console.log("提交的单位值:", this.form.unit, "映射到material_unit:", submitData.material_unit);
          
          // 处理物料分类 - 增强版
          // 首先检查表单中的分类ID数组
          if (this.form.categoryId && this.form.categoryId.length > 0) {
            console.log("从categoryId数组处理分类:", this.form.categoryId);
            
            // 检查是否同时有父类和子类
            if (this.form.categoryId.length >= 2) {
              // 有父类和子类，分别获取ID
              const parentId = this.form.categoryId[0]; // 第一个是父类ID
              const childId = this.form.categoryId[1]; // 第二个是子类ID
              
              // 设置父类ID
              submitData.material_classification_id = parentId;
              // 设置子类ID
              submitData.material_subcategory_id = childId;
              
              console.log("同时选择了父类和子类:", 
                         "父类ID:", submitData.material_classification_id, 
                         "子类ID:", submitData.material_subcategory_id);
              
              // 查找分类名称
              const parentCategory = this.parentCategories.find(p => 
                p.material_classification_id === parentId || p.id === parentId);
              
              const childCategory = this.childCategories.find(c => 
                c.material_subcategory_id === childId || c.id === childId);
              
              if (parentCategory && childCategory) {
                // 组合父类和子类名称
                submitData.material_fl = `${parentCategory.material_classification_name} / ${childCategory.material_subcategory_name}`;
              } else if (childCategory) {
                submitData.material_fl = childCategory.material_subcategory_name;
              } else if (parentCategory) {
                submitData.material_fl = parentCategory.material_classification_name;
              }
              
              console.log("设置物料分类名称:", submitData.material_fl);
            } else {
              // 只有一个ID，假设是父类ID
              const categoryId = this.form.categoryId[0];
              
              // 在整个分类树中查找匹配的分类
              const findCategory = (nodes, id) => {
                if (!nodes || !Array.isArray(nodes)) return null;
                
                for (const node of nodes) {
                  // 检查当前节点
                  if ((node.material_classification_id && node.material_classification_id === id) || 
                      (node.material_subcategory_id && node.material_subcategory_id === id) || 
                      node.id === id) {
                    return node;
                  }
                  
                  // 递归检查子节点
                  if (node.children && node.children.length > 0) {
                    const found = findCategory(node.children, id);
                    if (found) return found;
                  }
                }
                return null;
              };
              
              // 查找分类信息
              const categoryInfo = findCategory(this.categoryTreeData, categoryId);
              
              if (categoryInfo) {
                // 判断是否为子分类
                const isSubcategory = !!categoryInfo.material_subcategory_id || 
                                  !!categoryInfo.parentId || 
                                  (categoryInfo.parent_id !== undefined && categoryInfo.parent_id !== null);
                
                if (isSubcategory) {
                  // 如果是子分类，需要同时设置父类ID和子类ID
                  submitData.material_subcategory_id = categoryInfo.material_subcategory_id || categoryId;
                  submitData.material_classification_id = categoryInfo.parent_id || categoryInfo.material_classification_id || categoryInfo.parentId;
                  console.log("选择了子分类:", 
                             "子类ID:", submitData.material_subcategory_id, 
                             "父类ID:", submitData.material_classification_id);
                } else {
                  // 如果是父分类，只设置父类ID
                  submitData.material_classification_id = categoryId;
                  // 清除可能存在的子分类ID
                  delete submitData.material_subcategory_id;
                  console.log("只选择了父分类:", 
                             "父类ID:", submitData.material_classification_id);
                }
                
                // 设置分类名称
                submitData.material_fl = categoryInfo.material_classification_name || 
                                        categoryInfo.material_subcategory_name;
                console.log("设置物料分类:", isSubcategory ? "子分类" : "父分类", 
                            "名称:", submitData.material_fl);
              } else {
                console.warn("未找到选中的物料分类信息:", categoryId);
              }
            }
          } 
          // 如果没有分类ID数组，但有selectedParentId和selectedChildId
          else if (this.selectedParentId || this.selectedChildId) {
            console.log("使用selectedParentId和selectedChildId设置分类");
            
            // 设置父类ID
            if (this.selectedParentId) {
              submitData.material_classification_id = this.selectedParentId;
              console.log("设置父类ID:", submitData.material_classification_id);
              
              // 查找父分类名称
              const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
              if (parentCategory) {
                // 先设置父类名称
                submitData.material_fl = parentCategory.material_classification_name;
              }
            }
            
            // 设置子类ID (如果有)
            if (this.selectedChildId) {
              submitData.material_subcategory_id = this.selectedChildId;
              console.log("设置子类ID:", submitData.material_subcategory_id);
              
              // 查找子分类名称
              const childCategory = this.childCategories.find(c => c.material_subcategory_id === this.selectedChildId);
              if (childCategory) {
                // 如果同时有父类和子类，组合名称
                if (submitData.material_fl) {
                  submitData.material_fl = `${submitData.material_fl} / ${childCategory.material_subcategory_name}`;
                } else {
                  submitData.material_fl = childCategory.material_subcategory_name;
                }
              }
            }
            
            console.log("最终设置的分类信息:", 
                       "父类ID:", submitData.material_classification_id,
                       "子类ID:", submitData.material_subcategory_id,
                       "分类名称:", submitData.material_fl);
          }
          // 尝试从materialCategory字段解析分类信息
          else if (this.form.materialCategory) {
            console.log("尝试从materialCategory解析分类信息:", this.form.materialCategory);
            
            // 如果是编辑模式，尝试从原始数据中获取分类ID
            if (this.form.id && this.form.rawData) {
              const rawData = this.form.rawData;
              console.log("检查原始数据中的分类ID:", rawData);
              
              // 检查各种可能的分类ID字段
              if (rawData.material_classification_id) {
                submitData.material_classification_id = rawData.material_classification_id;
                console.log("从原始数据中获取父分类ID:", submitData.material_classification_id);
              } else if (rawData.basicWlfl && rawData.basicWlfl.material_classification_id) {
                submitData.material_classification_id = rawData.basicWlfl.material_classification_id;
                console.log("从嵌套对象basicWlfl中获取父分类ID:", submitData.material_classification_id);
              } else if (rawData.categoryId) {
                submitData.material_classification_id = rawData.categoryId;
                console.log("从categoryId字段获取父分类ID:", submitData.material_classification_id);
              }
              
              // 检查各种可能的子分类ID字段
              if (rawData.material_subcategory_id) {
                submitData.material_subcategory_id = rawData.material_subcategory_id;
                console.log("从原始数据中获取子分类ID:", submitData.material_subcategory_id);
              } else if (rawData.basicWlflz && rawData.basicWlflz.material_subcategory_id) {
                submitData.material_subcategory_id = rawData.basicWlflz.material_subcategory_id;
                console.log("从嵌套对象basicWlflz中获取子分类ID:", submitData.material_subcategory_id);
              } else if (rawData.subcategoryId) {
                submitData.material_subcategory_id = rawData.subcategoryId;
                console.log("从subcategoryId字段获取子分类ID:", submitData.material_subcategory_id);
              }
            }
            
            // 设置分类名称
            submitData.material_fl = this.form.materialCategory;
          } else {
            console.log("未选择物料分类");
          }
          
          // 确保必要的分类字段存在
          if (submitData.material_classification_id) {
            // 如果有分类ID，确保后端字段映射正确
            // 有些后端API可能需要这些字段
            submitData.basicWlfl = {
              material_classification_id: submitData.material_classification_id
            };
            
            if (submitData.material_subcategory_id) {
              submitData.basicWlflz = {
                material_subcategory_id: submitData.material_subcategory_id
              };
            }
          }
          
          console.log("最终提交数据:", submitData);
          
          if (this.form.id != undefined) {
            updateMaterial(submitData).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("修改失败", error);
              this.$message.error("修改失败: " + error.message);
            });
          } else {
            addMaterial(submitData).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增失败", error);
              this.$message.error("新增失败: " + error.message);
            });
          }
        }
      });
    },
    
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料";
      // 默认设置状态为启用
      this.form.status = '启用';
      this.form.material_status = '1'; // 设置material_status为启用
     

      // 不再自动调用getAutoCode()
    },
    
    // 修改按钮操作
    handleEdit(row) {
      this.reset();
      const id = row.id || row.materialCode;
      
      // 调试日志，帮助排查ID问题
      console.log("编辑物料原始数据:", row);
      console.log("物料ID:", id);
      if (row.rawData) {
        console.log("原始数据中的ID:", row.rawData.material_id || row.rawData.id);
      }
      
      // 调用getMaterialById获取物料数据
      getMaterialById(id).then(response => {
        console.log("获取物料数据结果:", response);
        if (response && response.data) {
          // 更新备注字段
          if (response.data.remarks) {
            this.form.remark = response.data.remarks;
            console.log("设置备注字段:", response.data.remarks);
          }
        }
      }).catch(error => {
        console.error("获取物料数据失败:", error);
      });
      
      // 将物料类型的显示值转换回数字编码
      let materialTypeValue = row.materialTypeValue || '';
      if (!materialTypeValue) {
        if (row.materialType === '生产物料') materialTypeValue = '1';
        else if (row.materialType === '半成品') materialTypeValue = '2';
        else if (row.materialType === '其他') materialTypeValue = '3';
      }
      
      // 将物料属性的显示值转换回数字编码
      let materialAttrValue = '';
      if (row.materialAttr === '自制') materialAttrValue = '1';
      else if (row.materialAttr === '委外') materialAttrValue = '2';
      else if (row.materialAttr === '外购') materialAttrValue = '3';
      else if (row.materialAttr === '其他') materialAttrValue = '4';
      else materialAttrValue = row.materialAttr;
      
      // 解析物料分类ID - 增强版
      let categoryId = [];
      
      console.log("开始解析物料分类ID:", row);
      
      if (row.rawData) {
        const rawData = row.rawData;
        console.log("物料原始数据中的分类信息:", {
          "material_classification_id": rawData.material_classification_id,
          "material_subcategory_id": rawData.material_subcategory_id,
          "categoryId": rawData.categoryId,
          "subcategoryId": rawData.subcategoryId,
          "basicWlfl": rawData.basicWlfl,
          "basicWlflz": rawData.basicWlflz
        });
        
        // 尝试从各种可能的字段获取父分类ID
        let parentId = null;
        if (rawData.material_classification_id) {
          parentId = rawData.material_classification_id;
        } else if (rawData.basicWlfl && rawData.basicWlfl.material_classification_id) {
          parentId = rawData.basicWlfl.material_classification_id;
        } else if (rawData.categoryId) {
          parentId = rawData.categoryId;
        }
        
        // 尝试从各种可能的字段获取子分类ID
        let childId = null;
        if (rawData.material_subcategory_id) {
          childId = rawData.material_subcategory_id;
        } else if (rawData.basicWlflz && rawData.basicWlflz.material_subcategory_id) {
          childId = rawData.basicWlflz.material_subcategory_id;
        } else if (rawData.subcategoryId) {
          childId = rawData.subcategoryId;
        }
        
        console.log("解析出的分类ID:", {
          "父分类ID": parentId,
          "子分类ID": childId
        });
        
        // 设置分类选择状态
        if (parentId && childId) {
          // 如果同时有父分类和子分类ID
          this.selectedParentId = parentId;
          this.selectedChildId = childId;
          categoryId = [parentId, childId];
          
          // 过滤子分类列表
          this.filterChildCategories();
          
          console.log("设置了父分类和子分类:", categoryId);
        } else if (parentId) {
          // 如果只有父分类ID
          this.selectedParentId = parentId;
          this.selectedChildId = null;
          categoryId = [parentId];
          
          // 过滤子分类列表
          this.filterChildCategories();
          
          console.log("只设置了父分类:", categoryId);
        } else {
          console.log("未找到分类ID");
        }
      } else {
        console.log("物料数据中没有原始数据");
      }
      
      // 获取正确的单位值
      const unitValue = row.unit || row.material_unit || '';
      console.log("编辑物料时的单位值:", unitValue);
      
      // 获取正确的物料ID
      let materialId = null;
      if (row.rawData && row.rawData.material_id) {
        materialId = row.rawData.material_id;
      } else {
        materialId = row.id;
      }
      console.log("使用的物料ID:", materialId);
      
      // 解析状态值 - 根据物料的实际状态设置
      let statusValue = '停用'; // 默认值
      
      // 优先使用表格中已处理好的状态值
      if (row.status === '启用' || row.status === '停用') {
        statusValue = row.status;
        console.log("使用表格中的状态值:", statusValue);
      } 
      // 其次检查原始数据
      else if (row.rawData) {
        if (row.rawData.status === '1' || row.rawData.status === 1 || 
            row.rawData.material_status === '1' || row.rawData.material_status === 1) {
          statusValue = '启用';
        } else if (row.rawData.status === '0' || row.rawData.status === 0 || 
                  row.rawData.material_status === '0' || row.rawData.material_status === 0) {
          statusValue = '停用';
        }
        console.log("从原始数据中解析状态值:", statusValue);
      }
      
      console.log("最终使用的状态值:", statusValue);
      
      // 直接从行数据映射字段
      this.form = {
        id: materialId, // 使用正确的物料ID
        material_id: materialId, // 确保同时设置material_id
        materialCode: row.materialCode,
        materialName: row.materialName,
        specification: row.specification,
        unit: unitValue,  // 确保使用正确的单位值
        materialType: materialTypeValue,  // 使用数字编码
        materialAttr: materialAttrValue,  // 使用数字编码
        materialCategory: row.materialCategory,
        categoryId: categoryId || row.categoryId || [],
        status: statusValue, // 使用解析后的状态值
        remark: row.remark || '',
        // 后端字段映射
        material_code: row.materialCode,
        material_name: row.materialName,
        material_sfn: row.specification,
        material_unit: unitValue,  // 确保使用正确的单位值
        material_mp: row.materialAttr,
        material_fl: row.materialCategory,
        material_type: materialTypeValue,  // 使用数字编码
        material_status: statusValue === '启用' ? '1' : '0', // 添加material_status字段映射
        // 保存原始数据，以便在提交时使用
        rawData: row.rawData
      };
      
      this.open = true;
      this.title = "修改物料";
      
      // 如果有rawData，使用原始数据的值覆盖
      if (row.rawData) {
        const rawData = row.rawData;
        console.log("编辑原始数据:", rawData);
        
        // 保留后端原始字段值
        this.form.material_code = rawData.material_code || rawData.gc001 || this.form.materialCode;
        this.form.material_name = rawData.material_name || this.form.materialName;
        this.form.material_sfn = rawData.material_sfn || this.form.specification;
        
        // 确保单位值正确
        const rawUnitValue = rawData.material_unit || rawData.unit || this.form.unit;
        this.form.material_unit = rawUnitValue;
        this.form.unit = rawUnitValue;
        console.log("从原始数据中获取单位值:", rawUnitValue);
        
        this.form.material_mp = rawData.material_mp || this.form.materialAttr;
        this.form.material_fl = rawData.material_fl || this.form.materialCategory;
        this.form.material_type = rawData.material_type || this.form.materialType; // 保留原始值
        
        // 确保material_status字段与状态一致
        this.form.material_status = this.form.status === '启用' ? '1' : '0';
        
        // 打印所有可能的状态字段，帮助调试
        console.log("状态字段值:", {
          'form.status': this.form.status,
          'material_status': this.form.material_status,
          'rawData.status': rawData.status,
          'rawData.material_status': rawData.material_status,
          'row.status': row.status
        });
      }
    },
    
    // 删除按钮操作
    handleDelete(row) {
      const id = row.id || row.materialCode;
      this.$confirm('是否确认删除物料编号为"' + row.materialCode + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteMaterial(id);
      }).then(() => {
        this.$message.success('删除成功');
        this.getList();
      }).catch(error => {
        console.error("删除失败", error);
      });
    },
    
    // 导入导出按钮操作函数已删除
    
    // 物料属性代码转文本
    getMaterialAttrText(attrCode) {
      switch(attrCode) {
        case '1': return '自制';
        case '2': return '委外';
        case '3': return '外购';
        case '4': return '其他';
        default: return attrCode; // 保持原值，以防数据不一致
      }
    },
    
    // 更新级联选择器选项
    updateCategoryOptions() {
      this.categoryOptions = this.convertTreeToOptions(this.categoryTreeData);
    },
    
    // 转换分类树为级联选择器选项
    convertTreeToOptions(treeData) {
      let options = [];
      if (!treeData || treeData.length === 0) return options;
      
      treeData.forEach(node => {
        // 排除根节点"全部物料"
        if (node.id === '0') {
          if (node.children && node.children.length > 0) {
            // 将根节点的子节点（即父分类）直接添加到选项中
            options = options.concat(this.convertTreeToOptions(node.children));
          }
          return;
        }
        
        // 创建选项对象 - 适配级联选择器
        let option = {
          id: node.material_classification_id || node.id,
          name: node.material_classification_name || node.material_subcategory_name || '未命名分类',
          code: node.material_classification_code || node.material_subcategory_code || '',
          isLeaf: !(node.children && node.children.length > 0)
        };
        
        // 添加子节点
        if (node.children && node.children.length > 0) {
          option.children = this.convertTreeToOptions(node.children);
        }
        
        options.push(option);
      });
      
      return options;
    },
    
    // 调试方法 - 打印分类树结构
    debugCategoryTree() {
      console.log("当前分类树结构:");
      const printNode = (node, level) => {
        const indent = '  '.repeat(level);
        const isSubcategory = node.isSubcategory || node.material_subcategory_id;
        const nodeType = isSubcategory ? "子分类" : "父分类";
        const nodeName = node.material_classification_name || node.material_subcategory_name || "未命名";
        const nodeCode = node.material_classification_code || node.material_subcategory_code || "no-code";
        
        console.log(`${indent}[${nodeType}] ${nodeName} (${nodeCode})`);
        
        if (node.children && node.children.length > 0) {
          console.log(`${indent}  包含 ${node.children.length} 个子节点:`);
          node.children.forEach(child => printNode(child, level + 1));
        }
      };
      
      this.categoryTreeData.forEach(node => printNode(node, 0));
      
      // 检查是否有子分类
      let hasSubcategories = false;
      const countSubcategories = (nodes) => {
        if (!nodes || !Array.isArray(nodes)) return 0;
        let count = 0;
        
        nodes.forEach(node => {
          if (node.children && node.children.length > 0) {
            count += node.children.length;
            count += countSubcategories(node.children);
          }
        });
        
        return count;
      };
      
      const totalSubcategories = countSubcategories(this.categoryTreeData);
      console.log(`分类树中共有 ${totalSubcategories} 个子分类`);
    },
    
    // 处理物料类型下拉框变化
    handleMaterialTypeChange(value) {
      console.log("物料类型变更为:", value);
      if (value) {
        // 将前端的materialType映射到后端的material_type参数
        this.queryParams.material_type = value;
        console.log("设置物料类型查询参数:", this.queryParams.material_type);
      } else {
        // 清除物料类型查询条件
        delete this.queryParams.material_type;
        console.log("清除物料类型查询参数");
      }
      
      // 可以选择立即查询，也可以等用户点击查询按钮
      // this.handleQuery();
    },
    
    // 加载单位选项
    loadUnitOptions() {
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '正在加载单位数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 设置加载超时
      const timeout = setTimeout(() => {
        loading.close();
        this.useBackupUnitOptions();
        this.$message.error("加载单位数据超时，已使用备用数据");
      }, 15000); // 15秒超时
      
      // 调用API获取所有单位
      listAllUnits().then(response => {
        // 清除超时计时器
        clearTimeout(timeout);
        
        console.log("获取单位选项返回数据:", response);
        
        // 解析返回数据
        let unitData = [];
        if (response && response.code === 200) {
          unitData = response.data || response.rows || [];
        } else if (response && response.rows) {
          unitData = response.rows;
        } else if (response && response.data) {
          unitData = response.data;
        } else if (Array.isArray(response)) {
          unitData = response;
        }
        
        // 如果成功获取单位数据，更新选项
        if (unitData && unitData.length > 0) {
          try {
            // 转换为选项格式
            this.unitOptions = unitData.map(item => {
              // 获取显示名称
              const displayName = item.unitName || item.unit_name || item.name || item.value || item.label || item;
              
              // 始终使用显示名称作为值，确保"吨"传到后端就是"吨"，而不是"dn"
              return {
                label: displayName,
                value: displayName
              };
            });
            
            // 确保有必要的单位选项
            this.ensureRequiredUnitOptions();
            
            console.log("处理后的单位选项:", this.unitOptions);
            loading.close();
          } catch (error) {
            console.error("处理单位数据时出错:", error);
            loading.close();
            this.useBackupUnitOptions();
          }
        } else {
          console.warn("未获取到单位数据，使用备用选项");
          loading.close();
          this.useBackupUnitOptions();
        }
      }).catch(error => {
        // 清除超时计时器
        clearTimeout(timeout);
        
        console.error("获取单位选项失败:", error);
        loading.close();
        this.useBackupUnitOptions();
        
        // 5秒后重试一次
        setTimeout(() => {
          this.retryLoadUnitOptions();
        }, 5000);
      });
    },
    
    // 确保必要的单位选项存在
    ensureRequiredUnitOptions() {
      const requiredOptions = [
        { label: '吨', value: '吨' },
        { label: '千克', value: '千克' },
        { label: '克', value: '克' },
        { label: 'sjef00', value: 'sjef00' }
      ];
      
      // 检查每个必要选项是否存在，不存在则添加
      requiredOptions.forEach(option => {
        const exists = this.unitOptions.some(item => 
          item.value === option.value || item.label === option.label
        );
        
        if (!exists) {
          this.unitOptions.push(option);
          console.log(`添加必要的单位选项: ${option.label}`);
        }
      });
    },
    
    // 重试加载单位选项
    retryLoadUnitOptions() {
      console.log("重试加载单位选项...");
      
      // 如果已经有单位选项数据，则不重试
      if (this.unitOptions && this.unitOptions.length > 0) {
        console.log("已有单位选项数据，不需要重试");
        return;
      }
      
      // 不显示加载状态，静默重试
      listAllUnits().then(response => {
        console.log("重试获取单位选项返回数据:", response);
        
        // 解析返回数据
        let unitData = [];
        if (response && response.code === 200) {
          unitData = response.data || response.rows || [];
        } else if (response && response.rows) {
          unitData = response.rows;
        } else if (response && response.data) {
          unitData = response.data;
        } else if (Array.isArray(response)) {
          unitData = response;
        }
        
        // 如果成功获取单位数据，更新选项
        if (unitData && unitData.length > 0) {
          try {
            // 转换为选项格式
            this.unitOptions = unitData.map(item => {
              // 获取显示名称
              const displayName = item.unitName || item.unit_name || item.name || item.value || item.label || item;
              
              // 始终使用显示名称作为值，确保"吨"传到后端就是"吨"，而不是"dn"
              return {
                label: displayName,
                value: displayName
              };
            });
            
            // 确保有必要的单位选项
            this.ensureRequiredUnitOptions();
            
            console.log("重试成功，处理后的单位选项:", this.unitOptions);
            this.$message.success("单位数据加载成功");
          } catch (error) {
            console.error("重试处理单位数据时出错:", error);
          }
        }
      }).catch(error => {
        console.error("重试获取单位选项失败:", error);
      });
    },
    
    // 使用备用单位选项
    useBackupUnitOptions() {
      // 设置备用单位选项
      this.unitOptions = [
        { label: '个', value: '个' },
        { label: '件', value: '件' },
        { label: '套', value: '套' },
        { label: 'kg', value: 'kg' },
        { label: 'm', value: 'm' },
        { label: '吨', value: '吨' },
        { label: '千克', value: '千克' },
        { label: '克', value: '克' },
        { label: 'sjef00', value: 'sjef00' }
      ];
      
      // 提示用户
      this.$message.warning("获取单位数据失败，已使用备用数据");
    },
    
    // 单位下拉框变化处理函数已删除

    // 物料分类级联选择器变化
    handleCategoryChange(value) {
      console.log("物料分类级联选择器变化，选中值:", value);
      
      if (value && value.length > 0) {
        // 最后一个值为选中的分类ID
        const categoryId = value[value.length - 1];
        
        // 查找选中的分类信息
        const findCategoryById = (categories, id) => {
          if (!categories || !Array.isArray(categories)) return null;
          
          for (const category of categories) {
            if (category.id === id) {
              return category;
            }
            
            if (category.children && category.children.length > 0) {
              const found = findCategoryById(category.children, id);
              if (found) return found;
            }
          }
          
          return null;
        };
        
        // 查找选中的分类
        const selectedCategory = findCategoryById(this.categoryOptions, categoryId);
        
        if (selectedCategory) {
          // 设置表单中的显示值
          this.form.materialCategory = selectedCategory.name;
          
          console.log("选中的分类:", selectedCategory);
        }
      } else {
        // 清空选择
        this.form.materialCategory = '';
      }
    },

    // 备用方法：尝试通过父分类API获取子分类数据
    loadChildCategoriesFallback() {
      console.log("尝试使用备用方法加载子分类数据...");
      
      // 使用listAllCategoriesWithChildren方法获取完整的分类结构
      listAllCategoriesWithChildren().then(response => {
        if (response && response.code === 200 && response.data) {
          // 提取所有子分类
          const allCategories = response.data || [];
          const extractedChildren = [];
          
          // 从完整分类结构中提取子分类
          allCategories.forEach(parent => {
            if (parent.children && Array.isArray(parent.children)) {
              parent.children.forEach(child => {
                // 确保子分类有正确的父分类ID
                child.parent_id = parent.material_classification_id;
                extractedChildren.push(child);
              });
            }
          });
          
          this.childCategories = extractedChildren;
          console.log("通过备用方法成功加载子分类:", this.childCategories);
          
          // 如果已选择父分类，更新过滤后的子分类
          if (this.selectedParentId) {
            this.filterChildCategories();
          }
          
          this.$message.success("物料分类数据加载成功");
        } else {
          console.warn("备用方法加载子分类失败:", response);
          this.$message.error("无法加载物料分类数据，请刷新页面重试");
        }
      }).catch(error => {
        console.error("备用方法加载子分类失败:", error);
        this.$message.error("无法加载物料分类数据，请联系系统管理员");
      });
    },

    // 父分类选择变化
    handleParentCategoryChange(value) {
      this.selectedParentId = value;
      this.filterChildCategories();
      this.selectedChildId = null; // 清除之前选择的子分类
      
      // 当选择父分类时，更新表单中的categoryId和materialCategory
      if (value) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === value);
        if (parentCategory) {
          // 只设置父类ID
          this.form.categoryId = [value];
          // 设置显示的分类名称
          this.form.materialCategory = parentCategory.material_classification_name;
          
          console.log("只选择了父类:", {
            "父类ID": value,
            "父类名称": parentCategory.material_classification_name,
            "categoryId数组": this.form.categoryId
          });
        }
      } else {
        // 清空分类选择
        this.form.categoryId = [];
        this.form.materialCategory = '';
      }
    },

    // 过滤子分类
    filterChildCategories() {
      if (!this.selectedParentId) {
        this.filteredChildCategories = [];
        return;
      }
      
      console.log("过滤子分类，父分类ID:", this.selectedParentId);
      console.log("所有子分类:", this.childCategories);
      
      this.filteredChildCategories = this.childCategories.filter(child => {
        const result = child.parent_id === this.selectedParentId || 
               child.material_classification_id === this.selectedParentId;
        
        if (result) {
          console.log("匹配的子分类:", child);
        }
        
        return result;
      });
      
      console.log("过滤后的子分类数量:", this.filteredChildCategories.length);
    },

    // 修改子分类选择方法，添加关闭弹出框功能
    handleChildCategoryChange(value) {
      if (value) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
        const childCategory = this.filteredChildCategories.find(c => c.material_subcategory_id === value);
        
        if (parentCategory && childCategory) {
          // 设置分类ID数组 - 确保父类ID在前，子类ID在后
          this.form.categoryId = [this.selectedParentId, value];
          
          // 设置显示的分类名称
          this.form.materialCategory = `${parentCategory.material_classification_name} / ${childCategory.material_subcategory_name}`;
          
          console.log("选择了父类和子类:", {
            "父类ID": this.selectedParentId,
            "父类名称": parentCategory.material_classification_name,
            "子类ID": value,
            "子类名称": childCategory.material_subcategory_name,
            "categoryId数组": this.form.categoryId
          });
          
          // 关闭弹出框
          this.$nextTick(() => {
            this.categoryPopoverVisible = false;
          });
        }
      }
    },

    // 处理自动编码开关变化
    handleAutoCodeChange(value) {
      if (value) {
        // 开启自动编码
        this.getAutoCode();
        
        // 如果页面上有错误提示，尝试从中提取编号
        setTimeout(() => {
          if (!this.form.materialCode) {
            const errorElements = document.querySelectorAll('.el-message--error .el-message__content');
            for (let i = 0; i < errorElements.length; i++) {
              const errorText = errorElements[i].textContent || '';
              const extractedCode = this.extractCodeFromErrorMessage(errorText);
              if (extractedCode) {
                this.form.materialCode = extractedCode;
                this.$message.success("已从错误提示中提取编号: " + extractedCode);
                return;
              }
            }
          }
        }, 500);
      } else {
        // 关闭自动编码，但不清空编码
        // 如果需要清空编码，可以取消注释下面这行
        // this.form.materialCode = '';
        
        // 提示用户物料编号是只读的
        this.$message.info("物料编号为只读字段，无法手动编辑");
      }
    },
    
    // 从错误提示中提取编号
    extractCodeFromErrorMessage(message) {
      if (!message) return null;
      
      // 尝试匹配 GC 开头的编号
      const gcMatch = message.match(/GC\d+/);
      if (gcMatch && gcMatch[0]) return gcMatch[0];
      
      // 尝试匹配其他可能的编号格式
      const numMatch = message.match(/\d{10,}/); // 匹配10位以上的数字
      if (numMatch && numMatch[0]) return numMatch[0];
      
      // 尝试匹配其他常见的物料编码格式
      const codeMatch = message.match(/[A-Z]{1,3}\d{4,}/);
      if (codeMatch && codeMatch[0]) return codeMatch[0];
      
      return null;
    },

    // 获取自动编码
    getAutoCode() {
      // 如果是编辑模式且已有物料编号，则不重新获取
      if (this.form.id && this.form.materialCode) {
        console.log("编辑模式，保留原物料编号:", this.form.materialCode);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为16（物料编号）
      getAutoNumbers(16).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.materialCode = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.materialCode = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.materialCode = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.materialCode = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.materialCode = "WLBH" + new Date().getTime(); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || '未知错误'));
      });
    },
  },
  watch: {
    selectedChildId(val) {
      if (val) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
        const childCategory = this.filteredChildCategories.find(c => c.material_subcategory_id === val);
        
        if (parentCategory && childCategory) {
          this.form.categoryId = [this.selectedParentId, val];
          this.form.materialCategory = `${parentCategory.material_classification_name} / ${childCategory.material_subcategory_name}`;
        }
      } else if (this.selectedParentId) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
        if (parentCategory) {
          this.form.categoryId = [this.selectedParentId];
          this.form.materialCategory = parentCategory.material_classification_name;
        }
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.search-container {
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.main-content {
  display: flex;
  min-height: calc(100vh - 180px);
}

.category-tree-container {
  width: 300px; /* 增加宽度从240px到300px */
  background-color: #ffffff;
  margin-right: 15px;
  border-radius: 4px;
  padding: 0 0 15px 0;
  overflow: auto; /* 允许滚动 */
  max-height: calc(100vh - 200px); /* 设置最大高度，避免过长 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.category-title {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: bold;
  color: #303133;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa; /* 添加背景色 */
  font-size: 16px; /* 增大字体 */
}

/* 刷新按钮样式 */
.category-title .el-button--text {
  padding: 5px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.category-title .el-button--text:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.material-table-container {
  flex: 1;
  background-color: #ffffff;
  border-radius: 4px;
  padding: 15px;
}

.title-container {
  margin-bottom: 15px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.table-operations {
  margin-bottom: 15px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0; /* 增加上下内边距 */
  width: 100%; /* 确保占满整个宽度 */
}

.category-code {
  font-size: 12px;
  color: #909399;
  margin-left: 6px;
  opacity: 0.9;
  font-family: 'Courier New', monospace; /* 使用等宽字体显示编码 */
}

/* 父分类与子分类样式区分 */
.el-tree-node__content {
  height: auto;
  min-height: 32px; /* 增加高度 */
  padding: 4px 0; /* 增加内边距 */
  margin: 2px 0; /* 增加节点间距 */
}

.parent-category {
  font-weight: bold;
  color: #303133;
  font-size: 15px; /* 增大父分类字体 */
}

.child-category {
  font-size: 14px; /* 增大子分类字体 */
  color: #606266;
  padding-left: 4px;
}

/* 高亮当前选中的节点 */
.el-tree-node.is-current > .el-tree-node__content {
  background-color: #ecf5ff !important;
  border-radius: 4px;
}

/* 鼠标悬停效果 */
.el-tree-node:focus > .el-tree-node__content {
  background-color: #f5f7fa;
}

/* 增加子分类的缩进和视觉区分 */
.el-tree-node__children .el-tree-node__content {
  padding-left: 8px;
  background-color: #fafafa;
  border-left: 2px solid #eaeaea; /* 添加左边框，增强层级感 */
  margin-left: 10px; /* 增加左边距 */
}

/* 树节点之间的间距 */
.el-tree-node:not(:last-child) {
  margin-bottom: 4px; /* 增加节点间距 */
}

/* 自定义展开图标 */
.el-tree-node__expand-icon {
  font-size: 16px;
  color: #409EFF;
  padding: 6px;
}

/* 展开图标悬停效果 */
.el-tree-node__expand-icon:hover {
  background-color: #ecf5ff;
  border-radius: 50%;
}

/* 整体树的样式 */
.category-tree {
  padding: 10px;
}

/* 树节点的悬停效果 */
.el-tree-node__content:hover {
  background-color: #f0f7ff !important;
}

/* 树节点的选中效果 */
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f2ff !important;
  font-weight: bold;
}

/* 根节点特殊样式 */
.el-tree-node[aria-level="1"] > .el-tree-node__content {
  border-bottom: 1px dashed #e0e0e0;
  margin-bottom: 5px;
  padding-bottom: 8px;
}

/* 分类选择器样式 */
.category-selector {
  display: flex;
  flex-direction: column;
}

.category-content {
  display: flex;
  height: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.parent-categories {
  width: 50%;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.parent-category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.parent-category-item:hover {
  background-color: #ecf5ff;
}

.parent-category-item .el-radio {
  margin-right: 0;
  width: calc(100% - 20px);
}

.child-categories {
  width: 50%;
  overflow-y: auto;
  background-color: #ffffff;
}

.child-category-item {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.child-category-item:hover {
  background-color: #ecf5ff;
}

.category-list-title {
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  position: sticky;
  top: 0;
  z-index: 1;
}

.category-name {
  font-size: 14px;
  display: inline-block;
  max-width: calc(100% - 60px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.category-code {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
  display: inline-block;
  max-width: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.category-input-reference {
  width: 100%;
}

.empty-child-tip {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 改进单选按钮组的样式 */
.category-selector .el-radio {
  margin-right: 0;
  width: 100%;
  white-space: normal;
  display: flex;
  align-items: center;
}

.category-selector .el-radio__label {
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 当没有子分类时显示提示 */
.no-subcategories {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.selected-preview {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
}

.preview-title {
  font-weight: bold;
  margin-right: 10px;
}

.preview-content {
  color: #409EFF;
}

/* 表格中的物料编号显示样式 - 保留但不使用，为了兼容性 */
.material-code-display {
  font-family: 'Courier New', monospace;
  font-weight: normal;
  letter-spacing: 0px;
  color: #333;
  display: block;
  width: 100%;
  text-align: center;
  font-size: 13px;
  transform: scale(0.95);
}

/* 表格中的物料编号新样式 */
.material-code-table {
  font-family: 'Courier New', monospace;
  font-weight: normal;
  color: #333;
  display: inline-block;
  width: 100%;
  text-align: center;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 130px;
}

.auto-code-switch {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 16px;
  padding: 2px 10px;
  border: 1px solid #dcdfe6;
}

.switch-label {
  font-size: 12px;
  margin-right: 5px;
  color: #606266;
}

.auto-code-input .el-switch {
  flex-shrink: 0;
}

/* 全局样式，美化物料编号的悬停提示 */
::v-deep .el-tooltip__popper {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  padding: 8px 12px;
}

/* 物料分类输入框样式 */
.category-select-box {
  width: 100%;
}

.category-select-box .el-input__inner {
  cursor: pointer;
}

/* 自动编码输入框样式 */
.auto-code-input {
  display: flex;
  align-items: center;
  width: 100%;
}

.auto-code-input .el-input {
  margin-right: 10px;
  flex: 1;
}

.material-code-input {
  width: 100%;
  font-size: 14px;
  font-weight: bold;
}

.material-code-input .el-input__inner {
  background-color: #f8f8f8;
  color: #333;
  letter-spacing: 0.5px;
  font-family: 'Courier New', monospace;
  font-size: 16px;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
  cursor: not-allowed; /* 添加禁用样式 */
}
</style>